package core

import (
	"gitee.com/cdsailyj/go-vpn/common/cfg"
	"github.com/redis/go-redis/v9"
	"sync"
)

type RedisClient struct {
	Client *redis.Client
	Once   sync.Once
}

func (client *RedisClient) NewClient(r cfg.Redis) *redis.Client {
	client.Once.Do(func() {
		client.Client = redis.NewClient(&redis.Options{
			Addr:     r.Addr,
			Password: r.Password,
			DB:       r.DB,
		})
	})
	return client.Client
}

var (
	clientMap = make(map[string]*RedisClient)
)

func GetRedis(r cfg.Redis) *redis.Client {
	if clientMap[r.Addr] == nil {
		clientMap[r.Addr] = &RedisClient{}
		clientMap[r.Addr].NewClient(r)
	}
	return clientMap[r.Addr].Client
}
